<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px"
        ></span>
        添加版本
      </p>
      <p slot="extra" style="color: #999; font-size: 12px">
        <label style="color: #ff3b30">*</label> 为必填
      </p>
      <Form
        ref="formValidate"
        :model="bloc.model"
        :rules="ruleValidate"
        :label-width="100"
      >
        <FormItem label="版本号：" prop="versionName" required>
          <Input
            :disabled="isEdit"
            v-model="bloc.model.versionName"
            style="width: 400px"
            placeholder="请注意输入格式:如(0.0.1)"
          />
        </FormItem>
        <FormItem label="版本编号：" prop="versionCode" required>
          <Input
            :disabled="isEdit"
            v-model="bloc.model.versionCode"
            style="width: 400px"
          />
        </FormItem>
        <FormItem label="更新类型：" prop="upgradeType" required>
          <RadioGroup v-model="bloc.model.upgradeType">
            <Radio :disabled="isEdit" label="APP">安卓APP</Radio>
            <Radio :disabled="isEdit" label="PAD">IPAD</Radio>
            <Radio :disabled="isEdit" label="IOS">苹果APP</Radio>
            <Radio :disabled="isEdit" label="S0601">S0601</Radio>
          </RadioGroup>
        </FormItem>
        <!-- <FormItem
          label="apkMd5"
          prop="apkMd5"
          v-if="
            bloc.model.upgradeType === 'APP' ||
              bloc.model.upgradeType === 'S0601'
          "
        >
          <Input
            :disabled="isEdit"
            v-model="bloc.model.apkMd5"
            style="width: 400px"
          />
        </FormItem> -->
        <FormItem
          label="更改状态："
          prop="updateStatus"
          required
          v-if="bloc.model.upgradeType != 'IOS'"
        >
          <RadioGroup v-model="bloc.model.updateStatus">
            <Radio :disabled="isEdit" label="1">不强制更新</Radio>
            <Radio :disabled="isEdit" label="2">强制更新</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem
          label="APK文件："
          prop="downloadUrl"
          required
          v-if="
            (bloc.model.upgradeType === 'APP' ||
              bloc.model.upgradeType === 'S0601') && !isEdit
          "
        >
          <Upload
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="512000"
            :format="['apk']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError1"
            :on-exceeded-size="handleMaxSize1"
            :on-progress="handleProgress"
            :on-success="handleSuccessFile"
            :on-error="handleError"
          >
            <Button icon="ios-filing" :disabled="elProgress">选择附件</Button>
          </Upload>
          <a v-if="bloc.model.extName" :href="bloc.model.url">{{
            bloc.model.extName
          }}</a>
          <p style="margin-left: 15px" v-if="!elProgress">支持 apk 格式</p>
          <p style="margin-left: 15px" v-if="elProgress">正在上传请等待...</p>
        </FormItem>
        <FormItem label="更改内容：" prop="modifyContent" required>
          <Input
            style="width: 400px"
            type="textarea"
            v-model="bloc.model.modifyContent"
            :rows="5"
            maxlength="50"
            show-word-limit
          ></Input>
        </FormItem>
        <FormItem label="富文本：" required>
          <HtmlEditor
            id="ueditor"
            :config="config"
            :content="initContent"
            :useCustomUpload="true"
            @change="ueditorChange"
            style="width: 100%; max-width: 1000px; overflow: auto"
          ></HtmlEditor>
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px">
        <router-link :to="{ path: '/apk' }">
          <Button style="width: 100px; height: 40px">返回</Button>
        </router-link>
        <Button
          style="margin-left: 30px; width: 100px; height: 40px"
          type="primary"
          :loading="btnload.loading"
          @click="handleSubmit('formValidate')"
          >保存
        </Button>
      </div>
    </Card>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import { ApkBloc } from "@/view/apk/ApkBloc";
import { store } from "@/store/Store";
import { baseUrl } from "@/base/Request";
import { Loading } from "@/base/Loading";
import { router } from "@/config/Router";
import HtmlEditor from "@/component/HtmlEditor.vue";

@Component({
  components: {
    HtmlEditor
  }
})
export default class extends Vue {
  @Prop({ type: Number })
  readonly init!: number;
  bloc = new ApkBloc();
  btnload = new Loading();
  initContent = "";
  snList: any = {
    1: "GY",
    2: "SQ",
    3: "SY",
    4: "ZW",
    5: "WZ",
    6: "ORDER"
  };
  formValidate: any = {
    type: "",
    switch: true
  };
  isEdit: any = "";
  config = {
    imageUrl: this.uploadActionImg, // 图片上传提交地址
    imagePath: "",
    imageToken: store.state.auth.accessToken,
    imageFieldName: "file"
  };
  validateVersions = (rule, value, callback) => {
    if (value === undefined) {
      callback(new Error("版本号不能为空"));
    } else {
      let reg2 = /^(\d+)\.(\d+)\.(\d+)$/;
      if (!reg2.test(value)) {
        callback(new Error("请输入正确的版本号如:0.0.1"));
      }
      callback();
    }
  };
  validateCode = (rule, value, callback) => {
    if (value === undefined) {
      callback(new Error("版本编码不能为空"));
    } else {
      let reg2 = /^[0-9]+$/;
      if (!reg2.test(value)) {
        callback(new Error("版本编码仅可输入纯数字"));
      }
      callback();
    }
  };
  ruleValidate: any = {
    modifyContent: [
      { required: true, message: "更改内容不能为空", trigger: "blur" }
    ],
    versionCode: [{ validator: this.validateCode, trigger: "blur" }],
    versionName: [{ validator: this.validateVersions, trigger: "blur" }],
    upgradeType: [
      { required: true, message: "更新类型不能为空", trigger: "blur" }
    ],
    downloadUrl: [
      { required: true, message: "APK文件不能为空", trigger: "blur" }
    ],
    updateStatus: [{ required: true, message: "状态不能为空", trigger: "blur" }]
  };
  $refs!: {
    formValidate: HTMLFormElement;
  };
  enable = true;
  elProgress = false;

  get uploadActionImg() {
    return `${baseUrl}/api/upload/image`;
  }

  get uploadHeaders() {
    return {
      Authorization: "Bearer " + store.state.auth.accessToken
    };
  }

  get uploadAction() {
    return `${baseUrl}/api/upload/apk`;
  }

  ueditorChange(ue) {
    this.bloc.model.detailedContent = ue.getContent();
    console.log(this.initContent)
  }

  handleMaxSize1(file) {
    this.$Message.error("文件大小不能超过200M");
  }
  handleFormatError1(file) {
    this.$Message.error("请选择格式为.apk格式的文件");
  }
  handleProgress() {
    this.elProgress = true;
  }
  handleError() {
    this.elProgress = false;
    this.$Message.error("上传失败");
  }
  handleSuccessFile(res, file) {
    this.elProgress = false;
    this.bloc.model.downloadUrl = res.data.url;
    this.bloc.model.apkSize = res.data.size;
    this.bloc.model.extName = res.data.extName;
  }

  handleSubmit(name) {
    // console.log(this.bloc.model);
    this.bloc.model.apkMd5 = ''
    this.$refs[name].validate(valid => {
      if (valid) {
        this.btnload.loading = true;
        if (this.isEdit) {
          this.bloc
            .putApkVersion(
              this.bloc.model.id,
              this.bloc.model.downloadUrl,
              this.bloc.model.apkSize,
              this.bloc.model.modifyContent,
              this.bloc.model.upgradeType,
              this.bloc.model.versionCode,
              this.bloc.model.versionName,
              this.bloc.model.apkMd5,
              Number(this.bloc.model.updateStatus),
              this.bloc.model.detailedContent
            )
            .then(res => {
              this.$Message.success("修改版本成功");
              this.btnload.loading = false;
              this.handleCancel();
            })
            .catch(err => {
              this.btnload.loading = false;
              if (err.name === "version_code_error") {
                this.$Message.error("修改版本失败," + err.message);
              } else {
                this.$Message.error("修改版本失败");
              }
            });
          // 修改
        } else {
          // 新增
          this.bloc
            .addApkVersion(
              this.bloc.model.downloadUrl,
              this.bloc.model.apkSize,
              this.bloc.model.modifyContent,
              this.bloc.model.upgradeType,
              this.bloc.model.versionCode,
              this.bloc.model.versionName,
              this.bloc.model.apkMd5,
              this.bloc.model.updateStatus,
              this.bloc.model.detailedContent
            )
            .then(res => {
              this.$Message.success("添加版本成功");
              this.btnload.loading = false;
              this.handleCancel();
            })
            .catch(err => {
              this.btnload.loading = false;
              if (err.name === "version_code_error") {
                this.$Message.error("添加版本失败," + err.message);
              } else {
                this.$Message.error("添加版本失败");
              }
            });
        }
      }
    });
  }
  handleCancel() {
    this.$router.push({
      path: "/apk"
    });
  }

  mounted() {
    this.isEdit = this.$route.query.isEdit ? true : false;
    if(!this.isEdit) return // 编辑状态才会赋值
    this.bloc.model.id = this.$route.query.id
    this.bloc.model.versionName = this.$route.query.versionName;
    this.bloc.model.versionCode = this.$route.query.versionCode;
    this.bloc.model.upgradeType = this.$route.query.upgradeType;
    this.bloc.model.updateStatus = this.$route.query.updateStatus;
    this.bloc.model.downloadUrl = this.$route.query.downloadUrl;
    this.bloc.model.apkSize = this.$route.query.apkSize;
    this.bloc.model.modifyContent = this.$route.query.modifyContent;
    this.bloc.model.apkMd5 = '';
    // console.log(this.$route.query.apkMd5);
    this.bloc.model.detailedContent = this.$route.query.detailedContent;
    const editor:any = document.querySelector('#ueditor')
    editor.innerHTML =this.$route.query.detailedContent
    // 根据id查询
  }
}
</script>
<style lang="less" scoped>
.top {
  height: 50px;
  width: 100%;
  border-bottom: 1px solid rgba(204, 204, 204, 1);
  font-size: 18px;
  line-height: 50px;
}

/deep/ .ivu-form-item-content {
  display: flex !important;
  justify-content: start !important;
  align-items: center !important;
}
</style>
